//
//  WHYStatusCellPictureView.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/11/26.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit
import SDWebImage

/// cell的间隙
private let WHYStatusCellPictureItemMargin: CGFloat = 8
/// cell的标示
private let WHYStatuwCellPictureItemCellID = "WHYStatuwCellPictureItemCellID"

class WHYStatusCellPictureView: UICollectionView {
    
    /// 微博视图模型
    var viewModel: WHYStatusViewModel? {
        didSet {
            
            sizeToFit()
            
            reloadData()
            
        }
    }
    
//    MARK: - 重写sizeThatFits函数
//    当调用sizeToFit时，系统会根据这个函数的返回值来计算视图的大小
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculateViewSize()
    }

//    MARK: - 构造函数
    init() {
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.minimumInteritemSpacing = WHYStatusCellPictureItemMargin
        flowLayout.minimumLineSpacing = WHYStatusCellPictureItemMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: flowLayout)
        
        backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        registerClass(WHYStatusCellPictureViewCell.self, forCellWithReuseIdentifier: WHYStatuwCellPictureItemCellID)
        
//MARK: 设置数据源和代理
        dataSource = self
        delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    

}

// MARK: - WHYPhotoBrowserPresentDelegate
extension WHYStatusCellPictureView: WHYPhotoBrowserPresentDelegate {
    
    /// 参与转场的图片框
    ///
    /// - parameter indexPath: 照片索引
    ///
    /// - returns: 参与转场动画的全新图片框
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView {
        let imageView = UIImageView()
        
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        
//        sd_setImageWithURL ： 会先去缓冲中取图片
        if let url = viewModel?.thumbnailUrls![indexPath.item] {
            imageView.sd_setImageWithURL(url)
        }
        
        imageView.sizeToFit()
        
        return imageView
    }
    
    /// 展现转场图片的起始位置
    ///
    /// - parameter indexPath: 照片索引
    ///
    /// - returns: 起始位置
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect {
        
        guard let cell = self.cellForItemAtIndexPath(indexPath) else {
            return CGRectZero
        }
        
//        将cell.frame从以WHYStatusCellPictureView作为参照转变成以UIApplication.sharedApplication().keyWindow!作为参照
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)

//        QL2(rect)
        
        return rect
    }
    
    /// 展现转场图片动画结束时的屏幕位置
    ///
    /// - parameter indexPath: 照片索引
    ///
    /// - returns: 相对于屏幕的位置
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect {
        
        guard let key = viewModel?.thumbnailUrls![indexPath.item].absoluteString else {
            return CGRectZero
        }
        
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        
        let w = UIScreen.mainScreen().bounds.width
        let h = w * image.size.height / image.size.width
        var y: CGFloat = 0
        
        let screenH = UIScreen.mainScreen().bounds.height
        
        if h < screenH {
            y = (screenH - h) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
    }
}

// MARK: - UICollectionViewDelegate
extension WHYStatusCellPictureView: UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //        QL2(viewModel?.thumbnailUrls![indexPath.item])
        
        NSNotificationCenter.defaultCenter().postNotificationName(WHYWBStatusSelectedPhotoNotification,
            object: self,
            userInfo: [WHYWBStatusSelectedPhotoURLKey: viewModel!.thumbnailUrls!,
                WHYWBStatusSelectedPhotoIndexPathKey: indexPath])
    }
    
}

// MARK: - UICollectionViewDataSource
extension WHYStatusCellPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier(WHYStatuwCellPictureItemCellID, forIndexPath: indexPath) as! WHYStatusCellPictureViewCell
        
        cell.imageURL = viewModel?.thumbnailUrls![indexPath.item]

        return cell
    }
    
}

// MARK: - 计算PictureView的高度
extension WHYStatusCellPictureView {
    
    private func calculateViewSize () -> CGSize {
        
//        每行3张图片
        let rowCount: CGFloat = 3
//        collectionView的总宽度
        let maxWidth = UIScreen.mainScreen().bounds.size.width - WHYStatusCellMagrin * 2
//        item的宽度
        let itemWidth = (maxWidth - WHYStatusCellPictureItemMargin * 2) / rowCount
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        let itemCount = viewModel?.thumbnailUrls?.count  ?? 0
        
        if itemCount == 0 {
            return CGSizeZero
        }
        
        if itemCount == 1 {
//  临时设置单图大小
            var size = CGSize(width: 150, height: 120)
            
            let key = viewModel?.thumbnailUrls?.first?.absoluteString
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                size = image.size
            }
            
            size.width > 40 ? size.width : 40
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * w / size.width
                size = CGSize(width: w, height: h)
            }
            
            layout.itemSize = size
            return size
        }
        
        if itemCount == 2 {
            let w  = CGFloat(itemCount) * itemWidth + WHYStatusCellPictureItemMargin
            return CGSize(width: w, height: itemWidth)
        }
        
        if itemCount == 4 {
            let w = itemWidth * 2 + WHYStatusCellPictureItemMargin
            return CGSize(width: w, height: w)
        }
        
        let row = CGFloat((itemCount - 1) / Int(rowCount) + 1)
//        为了让iPhone6+的设备也能正常的图片，将宽高各加 1 
        let w = rowCount * itemWidth + (rowCount - 1) * WHYStatusCellPictureItemMargin + 1
        let h = row * itemWidth + (row - 1) * WHYStatusCellPictureItemMargin + 1
        

        return CGSize(width: w, height: h)
    }
    
}

// MARK: - UICollectionViewCell
private class WHYStatusCellPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            
            iconView.sd_setImageWithURL(imageURL!, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.LowPriority])
            
//            根据文件的扩展名来判断，但是不是所有的gif都会动
            gifIconView.hidden = (imageURL?.absoluteString ?? "" as NSString).lastPathComponent.lowercaseString != "gif"
        }
    }
    
//    MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - 设置UI
    private func setupUI() {
        addSubview(iconView)
        iconView.addSubview(gifIconView)
        
//        iconView.snp_makeConstraints { (make) -> Void in
//            make.edges.equalTo(contentView.snp_edges)
//        }

        iconView.frame = bounds
        
        gifIconView.snp_makeConstraints { (make) -> Void in
            make.right.bottom.equalTo(iconView)
        }
    }
    
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
    
    private lazy var gifIconView: UIImageView = UIImageView(imageName: "timeline_image_gif")
    
    
}




